<template>
  <div class="accountManagement">
    <div class="accountManagement_main">
      <div class="accountManagement_main_title">
        <h1>账号管理</h1>
      </div>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="个人信息" class="activeName_one" name="first">
          <el-form :model="user" :rules="rules" ref="user" label-position="100px" class="demo-ruleForm">
            <div class="basic">
              <span>基本信息</span>
            </div>
            <el-form-item label="用户名:" prop="username" class="user_list">
              <el-input v-if="user.edit" v-model="user.username" style="width: 200px"></el-input>
              <span v-if="!user.edit">{{user.username}}</span>
            </el-form-item>
            <el-form-item label="真名:" prop="rname" class="user_list">
              <el-input v-if="user.edit" v-model="user.rname" style="width: 200px"></el-input>
              <span v-if="!user.edit">{{user.rname}}</span>
            </el-form-item>
            <el-form-item label="邮箱:" prop="email" class="user_list">
              <el-input v-if="user.edit" v-model="user.email" style="width: 300px"></el-input>
              <span v-if="!user.edit">{{user.email}}</span>
            </el-form-item>
            <el-form-item label="电话:" prop="phone" class="user_list">
              <el-input v-if="user.edit" v-model="user.phone" style="width: 300px"></el-input>
              <span v-if="!user.edit">{{user.phone}}</span>
            </el-form-item>
            <div class="basic">
              <span>学校信息</span>
            </div>
            <el-form-item label="学校:" prop="school" class="user_list">
              <el-input v-if="user.edit" v-model="user.school" style="width: 300px"></el-input>
              <span v-if="!user.edit">{{user.school}}</span>
            </el-form-item>
            <el-form-item label="专业:" prop="sex" class="user_list">
              <el-input v-if="user.edit" v-model="user.sex" style="width: 300px"></el-input>
              <span v-if="!user.edit">{{user.sex}}</span>
            </el-form-item>
<!--            <el-form-item label="年级:" prop="grade" class="user_list">-->
<!--              <el-input v-if="user.edit" v-model="user.grade" style="width: 300px"></el-input>-->
<!--              <span v-if="!user.edit">{{user.grade}}</span>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="学号:" prop="studentID" class="user_list">-->
<!--              <el-input v-if="user.edit" v-model="user.studentID" style="width: 300px"></el-input>-->
<!--              <span v-if="!user.edit">{{user.studentID}}</span>-->
<!--            </el-form-item>-->
            <el-form-item class="user_button">
              <el-button v-if="!user.edit" type="primary" @click="editButton">编辑</el-button>
              <el-button v-if="user.edit" type="success" @click="submitForm('user')">保存</el-button>
              <el-button v-if="user.edit" @click="Cancel">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="修改密码" class="activePassword" name="second">
          <div class="user-from">
            <el-form label-position="right" :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="旧密码:" prop="oldpassword">
                <el-input placeholder="请设置您的密码" type="password" v-model="ruleForm.oldpassword" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="密码:" prop="password">
                <el-input placeholder="请设置您的密码" type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="请确认密码:" prop="checkPass">
                <el-input placeholder="确认您的密码" type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button class="form-bottom" type="success" @click="submitForm2('ruleForm')">提交修改</el-button>
              </el-form-item>
              <el-form-item>
                <el-button class="form-bottom" type="primary" @click="resetForm('ruleForm')">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>

    </div>
  </div>
</template>

<script>


export default {
  name: "accountManagement",
  data() {

    //密码验证
    const validatePass = (rule, value, callback) => {
      if (this.ruleForm.checkPass !== '') {
        this.$refs.ruleForm.validateField('checkPass');
      }
      callback();
      // }
    };
    const validatePass2 = (rule, value, callback) => {
      // if (value === '') {
      //   callback(new Error('请再次输入密码'));
      // } else
      if (value !== this.ruleForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };

    //用户名表单验证
    const Username = (rule, value, callback) => {
      const pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]");
      // if (!value) {
      //   return callback(new Error('用户名不能为空'));
      // } else
      if (pattern.test(value)) {
        return callback( new Error('用户名不能包含特殊字符'))
      } else if (value.length>=16) {
        return  callback( new Error('用户名不能大于16个字符'))
      }
      callback()
    };
    //用户名表单验证

    //手机号验证
    const phoneValidator = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (!regMobile.test(value)) {
        return callback(new Error('手机号格式错误'));
      }
      callback();
    }
    //手机号验证

    return{
      activeName: 'first', // 控制Tabs标签
      user:{
      },
      ruleForm: {
        oldpassword:'',
        password: '',
        checkPass: '',
      },  // 修改密码
      rules: {
        username: [
            { required: true, message: '用户名不能为空', trigger: 'blur' },
          {validator: Username, trigger: 'blur'}
        ],
        rname: [
          { required: true, message: '真名不能为空', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        phone: [
          { required: true, message: '电话不能为空', trigger: ['blur', 'change'] },
          { validator: phoneValidator, trigger: 'blur'}
        ],
        school: [
          { required: true, message: '学校不能为空', trigger: 'blur' },
        ],
        sex: [
          { required: true, message: '专业不能为空', trigger: 'blur' },
        ],
        // studentID: [
        //   { required: true, message: '学号不能为空', trigger: 'blur' },
        // ],
        // grade: [
        //   { required: true, message: '年级不能为空', trigger: 'blur' },
        // ],
        oldpassword:[
          {required: true, message: '请输入旧密码', trigger: 'blur'},
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          {required: true, message: '请再次输入密码', trigger: 'blur'},
          { validator: validatePass2, trigger: 'blur' }
        ],
      }
    }
  },
  methods: {
    //Tabs控件
    handleClick(tab, event) {
      console.log('Tab',tab,'event', event);
    },
    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate( async (valid) => {
        if (valid) {
          const data = {...this.user};
          delete data.edit;
          delete data.userId;
          delete data.level;
          console.log(data);
          const res = await this.$api.changeUser(data);
          console.log(res);
          if(res.success){

            this.$message.success("修改成功");
          }
          this.user.edit = false;
        } else {
          this.$message.warning("修改失败");
          return false;
        }
      });
    },

    //表单重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //修改密码
    submitForm2(formName) {
      this.$refs[formName].validate(async (valid) => {

        if (valid) { //this.ruleForm
          // this.$api.register(this.ruleForm)
          //     .then(res=>{
          //       if(res.success){
          //         this.$message.success("注册成功！")
          //       }
          //     })
          const data = {password:this.ruleForm.oldpassword, updateword:this.ruleForm.password};
          const res = await this.$api.changePassword(data);
          if(res.success){
            this.$message.success("修改成功！");
          }else {
            this.$message.warning(res.describe);
          }
        } else {
          this.$message.warning("修改失败！")
          return false;
        }
      });
    },

    // 取消
    Cancel() { // formName
      this.user.edit = false;
    },

    // 编辑
    editButton(){
      this.user.edit = true;
    },

    // 获取用户信息
    // studentID: '2020221843',
    // grade: '大二',
    // edit: false
    async getUserInformation(){
      // const data =
      const res = await this.$api.getUserInformation(window.sessionStorage.getItem('userID'));
      let user = res.data.user;
      // user.studentID = '';
      // user.grade = '';
      user.edit = false;
      this.user = {...user};
    }
  },
  mounted() {
    this.getUserInformation();
  }
}
</script>

<style lang="less" scoped>
.accountManagement{
  background-color: #f7f9fa;
  box-sizing: border-box;
  height: 100%;
  padding: 20px;
  .accountManagement_main{
    .accountManagement_main_title{
      font-size: 15px;
      text-align: center;
    }
    box-shadow: 0 2px 7px rgba(187, 172, 172, 0.49), 0 5px 11px rgba(247, 231, 231, 0.36);
    width: 1200px;
    height: 900px;
    margin: 0 auto;
    padding: 20px;
    background-color: #ffffff;
    .activeName_one{
      .demo-ruleForm{
        margin: 100px auto;
        width: 1000px;
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        .user_list{
          width: 490px;
        }
        .basic{
          width: 1000px;
          font-size: 25px;
          font-weight: bolder;
          border-left: 10px solid #1e6c22;
          padding-left: 10px;
          margin-bottom: 30px;
        }
        .user_button{
          margin: 40px auto;
        }
      }
    }
    .activePassword{
      .user-from{
        width: 500px;
        margin: 100px auto;
        .demo-ruleForm{
          .form-bottom{
            width: 400px;
          }
        }
      }
    }

  }
}

</style>
